package com.hroze.util.web;

import java.io.File;
import java.util.Iterator;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

/**
 * @author zhwang E-mail:695w@163.com
 * 
 * @version 0.1 biuld 2009.12.17
 * 
 */

public class SystemConfig implements ServletContextListener {
	public static Prop CONFIG;
	private static ServletContext context = null;
	private static boolean initialized = false;
	public static String APP_REAL_PATH = null;
	private static String CONTEXT_PATH = null;
	/**
	 * 本地主机地址，默认127.0.0.1,如果映射了域名，可以在填写域名
	 */
	private static String HOST = "127.0.0.1";
	/**
	 * 应用程序在tomcat中主机，默认为localhost
	 */
	private static String APP_HOST = "localhost";
	private static Logger log;
	private static String URL;
	/**
	 * 端口号
	 */
	private static String PORT;

	/**
	 * tomcat路径
	 */
	private static String TOMCAT_HOME;

	public void contextDestroyed(ServletContextEvent event) {
		log.info("application Destroyed....");
	}

	public void contextInitialized(ServletContextEvent event) {
		context = event.getServletContext();
		CONFIG = new Prop(getClassRealPath("/config.properties"));
		APP_REAL_PATH = context.getRealPath("/");
		CONFIG.set("APP_REAL_PATH", APP_REAL_PATH);
		Prop log4j = new Prop(getClassRealPath("/log4j.properties"));
		log4j.set("log4j.appender.FILE.File", APP_REAL_PATH + "log4j.log");
		log4j.save();
		log = Logger.getLogger(SystemConfig.class);
		log.info("Initializeing.....");
		initialized = true;
		log.info("APP_REAL_PATH:" + APP_REAL_PATH);
		// 自动取TOMCAT路径，取不出来时才去配置文件中找
		TOMCAT_HOME = System.getenv("CATALINA_HOME");
		if (TOMCAT_HOME == null) {
			TOMCAT_HOME = CONFIG.get("TOMCAT_HOME");
		}
		System.out.println("TOMCAT_HOME:" + TOMCAT_HOME);
		CONFIG.set("TOMCAT_HOME", TOMCAT_HOME);
		CONTEXT_PATH = context.getContextPath();
		PORT = this.findPort();
		CONFIG.set("PORT", PORT);

		String host = CONFIG.get("HOST");
		if (host != null && !host.equals("")) {
			HOST = host;
		}
		CONFIG.set("HOST", HOST);
		System.out.println("HOST:" + HOST);
		URL = "http://" + HOST + ":" + PORT + CONTEXT_PATH;
		System.out.println("URL:" + URL);
		CONFIG.set("URL", URL);
		CONFIG.save();

	} 

	private String findPort() {
		String portstr = "";
		String path = TOMCAT_HOME;
		SAXReader saxReader = new SAXReader();
		// 先通过 org.dom4j.io.SAXReader 读入整份XML文档
		Document document = null;
		try {
			System.out.println("path:" + TOMCAT_HOME);
			if (TOMCAT_HOME.indexOf("%20") != -1) {
				TOMCAT_HOME = TOMCAT_HOME.replace("%20", " ");
			}
			path = TOMCAT_HOME + System.getProperty("file.separator") + "conf"
					+ System.getProperty("file.separator") + "server.xml";
			document = saxReader.read(new File(path));
			Element port = document.getRootElement();
			Element a = port.element("Service");
			Iterator<?> i = a.elementIterator();
			while (i.hasNext()) {
				Element element = (Element) i.next();
				if (element.getName().equals("Connector")) {
					if (element.attributeValue("protocol").indexOf("HTTP") != -1) {
						portstr = element.attributeValue("port");
						System.out.println("port:" + portstr);
						break;
					}
				}
			}
			// 虚拟主机
			Element engine = a.element("Engine");
			Iterator<?> hIt = engine.elementIterator();
			while (hIt.hasNext()) {
				Element element = (Element) hIt.next();
				Iterator<?> cIt = element.elementIterator();
				while (cIt.hasNext()) {
					Element e = (Element) cIt.next();
					if (e.getName().equals("Context")) {
						String p = e.attributeValue("path");
						String docBase = e.attributeValue("docBase");
						if (p.trim().equals(CONTEXT_PATH.trim())) {
							docBase.replaceAll("/", "\\");
							if (!docBase.endsWith("\\")) {
								docBase = docBase + "\\";
							}
							if (docBase.trim().equalsIgnoreCase(
									APP_REAL_PATH.trim())) {
								String xmlHost = element.attributeValue("name");
								if (xmlHost.equals("localhost")) {
									HOST = "127.0.0.1";

								} else {
									HOST = xmlHost;
									APP_HOST = HOST;
								}
								System.out.println("APP_HOST:" + xmlHost);
							}
							break;
						}
					}
				}
			}

		} catch (DocumentException e) {
			e.printStackTrace();
		}
		// 取得XML文档的根元素
		return portstr;
	}

	/**
	 * 获取web应用中classes下文件的绝对路径
	 * 
	 * @param path
	 *            相对路径以"/"开头
	 * @return
	 */
	public static String getClassRealPath(String path) {
		return getRealPath("/WEB-INF/classes" + path);
	}

	/**
	 * 获取WEB-INF下文件的绝对路径
	 * 
	 * @param path
	 *            相对路径如：位于WEB-INF下的l.text，path为："/1.text"
	 * @return
	 */
	public static String getWEBINFRealPath(String path) {
		return getRealPath("/WEB-INF" + path);
	}

	/**
	 * 获取应用程序的绝对路径
	 * 
	 * @return
	 */
	public static String getAppRealPath() {
		return APP_REAL_PATH;
	}

	/**
	 * 获取应用程序中某个文件的绝对路径
	 * 
	 * @param path
	 *            文件的相对路径如根目录下的文件"/a.jsp"
	 * @return
	 */
	public static String getRealPath(String path) {
		return context.getRealPath(path);
	}

	/**
	 * 获取应用程序的ServletContext对象
	 * 
	 * @return
	 */
	public static ServletContext getServletContext() {
		if (!initialized)
			throw new IllegalStateException(
					"   ServletContext   not   initialized.");
		return context;
	}

	public static String getPort() {
		return PORT;
	}

	public static String getHOST() {
		return HOST;
	}

	public static String getURL() {
		return URL;
	}

	public static String getAPP_REAL_PATH() {
		return APP_REAL_PATH;
	}

	public static String getCONTEXT_PATH() {
		return CONTEXT_PATH;
	}

	public static String getAPP_HOST() {
		return APP_HOST;
	}

	public static String getTOMCAT_HOME() {
		return TOMCAT_HOME;
	}

}
